﻿using ServiceStack.Redis;
using SYH.IBLL;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SYH.RedisCache
{
    /// <summary>
    /// Redis缓存服务
    /// </summary>
    public class CacheService : ICache
    {
        private readonly string HOST = ConfigurationManager.AppSettings["RedisHost"];
        /// <summary>
        /// 获取缓存数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Get<T>(string key)
        {
            using (RedisClient client = new RedisClient(HOST))
            {
                return client.Get<T>(key);
            }
        }
        /// <summary>
        /// 获取缓存数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public IList<T> GetList<T>(string key)
        {
            using (RedisClient client = new RedisClient(HOST))
            {
                return client.Get<List<T>>(key);
            }
        }
        /// <summary>
        /// 清除缓存
        /// </summary>
        /// <param name="key"></param>
        public void Remove(string key)
        {
            using (RedisClient client = new RedisClient(HOST))
            {
                client.Del(key);
            }
        }
        /// <summary>
        /// 写入缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="data"></param>
        public void Set<T>(string key, T data)
        {
            using (RedisClient client = new RedisClient(HOST))
            {
                client.Set<T>(key, data);
            }
        }

        /// <summary>
        /// 写入缓存定时清除
        /// </summary>
        /// <param name="key"></param>
        /// <param name="data"></param>
        /// <param name="timeout"></param>
        public void Set<T>(string key, T data, int timeout)
        {
            using (RedisClient client = new RedisClient(HOST))
            {
                client.Set<T>(key, data);
            }
        }

        /// <summary>
        /// 获取所有键集合
        /// </summary>
        /// <returns></returns>
        public List<string> Keys()
        {
            using (RedisClient client = new RedisClient(HOST))
            {
                return client.SearchKeys("*");
            }
        }
    }
}
